import VisualHelper from "./VisualHelper";

class Table2DHelper extends VisualHelper{

  initAttributes(){
    const visual = this.props.visual;
    let attributes = [];

    const row = parseInt(visual.row);
    const col = parseInt(visual.col);

    // console.log('.', row, col);

    for(var key in visual.attributes){
      // 特殊处理单元格属性
      if(key.indexOf('border') !== -1 || key.indexOf('Color') !== -1){
        const style = visual.tableDomElement.getStyle(row, col);
        if(!style) continue;

        const newAttribute = {
          key      :key, 
          value    :style[key], 
          type     :visual.attributes[key].type, 
          group    :visual.attributes[key].group,
          readOnly :visual.attributes[key].readOnly,
        }
        // console.log('.', row, col, newAttribute);
        attributes.push(newAttribute);
      }
      else{
        const newAttribute = {
          key      :key, 
          value    :visual.attributes[key].value, 
          type     :visual.attributes[key].type, 
          group    :visual.attributes[key].group,
          readOnly :visual.attributes[key].readOnly,
        }
        attributes.push(newAttribute);
      }   
      
    }
    this.attributes = attributes;

    const groupedAttributes = this.groupAttributes(attributes, this.state.columns);

    // console.log('属性值：', attributes);
    this.setState({
      // attributes        : attributes,
      groupedAttributes : groupedAttributes
    });
  }

  handleValueChanged(event){
    const key = event.target.id;

    const attributes = this.attributes;
    var value =  event.target.value;
    if(event.target.type === 'checkbox'){
      value = event.target.checked;
    }
    for(var i=0, il=attributes.length; i < il; i++){
      if(attributes[i].key === key){
        attributes[i].value = value;
        break;
      }
    }
    const groupedAttributes = this.groupAttributes(attributes, this.state.columns);

    if(key === 'showHelper'){
      this.setState({
        showHelper        : value,
        // attributes        : attributes,
        groupedAttributes : groupedAttributes,
      });
    }
    else if(key === 'col'){
      if(value <= 0) value = 0;
      if(value >= this.props.visual.cols) value = this.props.visual.cols;
      this.props.visual[key] = value;
      this.refreshButton.current.click();
    }
    else if(key === 'row'){
      if(value <= 0) value = 0;
      if(value >= this.props.visual.rows) value = this.props.visual.rows;
      this.props.visual[key] = value;
      this.refreshButton.current.click();
    }
    else{
      this.updateButton.current.click();  
    }
  }
}

export default Table2DHelper;